package net.schastny.shopmanager.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import net.schastny.shopmanager.domain.BaseOrder;
import net.schastny.shopmanager.domain.Order;

@Repository
public class OrderDAOImlp implements OrderDAO {
	/*Аннотация позволяет автоматически установить значение поля SessionFactory.
	 */
	@Autowired
	private SessionFactory sessionFactory;
	
	public void addOrder(Integer pid,Order order) {
		// TODO Auto-generated method stub
		//sessionFactory.getCurrentSession().save(order);
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
	
		// Persists to db
		session.save(order);
		
		// Add to person as well
		// Retrieve existing person via id
		BaseOrder existingBaseOrder = (BaseOrder) session.get(BaseOrder.class, pid);
		
		// Assign updated values to this person
		existingBaseOrder.getOrders().add(order);

		// Save updates
		session.save(existingBaseOrder);
	
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Order> listOrder() {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession().createQuery("from Order")
	            .list();
	}

	
	
	public void removeOrder(Integer id) {
		// TODO Auto-generated method stub
		Order order = (Order) sessionFactory.getCurrentSession().load(
				Order.class, id);
        if (null != order) {
            sessionFactory.getCurrentSession().delete(order);
	}
	}

	public List<Order> getAll(Integer pid) {
		// TODO Auto-generated method stub
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Create a Hibernate query (HQL)
		Query query = session.createQuery("FROM BaseOrder as p LEFT JOIN FETCH  p.orders WHERE p.id="+pid);
		
		BaseOrder baseOrder = (BaseOrder) query.uniqueResult();
		System.out.println("----------------------baseOrder.getOrders().size() "+baseOrder.getOrders().size());
		// Retrieve all
		return  new ArrayList<Order>(baseOrder.getOrders());

	}
	
	
}
